'''
Created on Sep 7, 2012

@author: DuongThanh
'''
import nltk
from tool.OutputResult import OutputResult
from nltk.classify.svm import *
trainFeatureMerge = "../../data/trainFeaturesMerged.csv"
testFeatureMerge  = "../../data/testFeaturesMerged.csv"
resultFile        =  "../../data/output_SVM.csv"

def getLabeledFeatures(fileName):    
    labeledFeatures = []
    # TRAIN THE MODEL 
    file1 = open(fileName)
    for line in file1:
        all = line.split(",")
        features = {}
        for i in range(0,(len(all)-1)):
            features[i] = all[i]
        label = all[len(all)-1]
        # a tuple 
        temp = (features,label)
        #print features
        #print label 
        # add this tuple to train Features
        labeledFeatures.append(temp)
    
    file1.close()
    return labeledFeatures
    
def runOnTestData(testFileName, classifier):
    # RUN ON TEST DATA
    file2 = open(testFileName)
    result = []
    for line in file2:
        all = line.split(",")
        features = {}
        for i in range(0,len(all)):
            features[i] = all[i]
        # a tuple 
        temp = (features)
        label = classifier.classify(temp)
        result.append(label)
        #print label
    file2.close()
    return result
    
# MAIN PART ###
###############
# Get labeled features     
labeledFeatures =   getLabeledFeatures(trainFeatureMerge)  
# Run classifier 
#classifier = nltk.SvmClassifier.train(labeledFeatures)
classifier = SvmClassifier.train(labeledFeatures)

# Get output 
result = runOnTestData(testFeatureMerge,classifier)
# Now making the result
output = OutputResult()
output.outputBaseOnSentenceLevelLabels(resultFile,result)